package com.radiant.service;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.google.inject.Inject;
import com.radiant.exceptions.RadiantRuntimeException;

public class PhotoServiceImpl implements PhotoService {

	@Inject
	private AmazonS3 s3;

	public PhotoServiceImpl() {
		super();
	}

	public String storePhoto(InputStream inputStream) {
		BufferedInputStream bis = new BufferedInputStream(inputStream);
		bis.mark(20);
		ImageInputStream iis;
		try {
			iis = ImageIO.createImageInputStream(bis);
			Iterator<ImageReader >iter = ImageIO.getImageReaders(iis);
			if (iter.hasNext()) {
				ImageReader reader = (ImageReader)iter.next();
				reader.setInput(iis);
				String formatName = reader.getFormatName();	
	            iis.close();
	
	            String key = "image_" + UUID.randomUUID() + "." + formatName;
	            System.out.println("Uploading a new object to S3 with key " + key);
	            ObjectMetadata objectMetadata = new ObjectMetadata();
	            objectMetadata.setContentType("image/" + formatName);
	            bis.reset();
	            s3.putObject(new PutObjectRequest(PhotoService.BUCKET_NAME, key, bis, objectMetadata));
	            bis.close();

	            StringBuffer objectURL =  new StringBuffer("http://s3.amazonaws.com");
	            objectURL.append("/").append(PhotoService.BUCKET_NAME).append("/").append(key);
	            return objectURL.toString();
			}
		} catch (IOException e) {
			throw new RadiantRuntimeException("Error storing photo in S3", e);
		}
		return null;
	}
}
